package org.soenea.doitall.domain.command;

import org.dsrg.soenea.domain.command.CommandError;
import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.command.impl.Command;
import org.dsrg.soenea.domain.helper.Helper;
import org.dsrg.soenea.domain.mapper.LostUpdateException;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.command.exception.CurrentUserNotInGroupException;
import org.soenea.doitall.domain.command.exception.GroupModifiedException;
import org.soenea.doitall.domain.model.group.*;
import org.soenea.doitall.domain.model.group.mapper.*;

public class EditGroupCommand extends Command {
	public EditGroupCommand(Helper helper) {
		super(helper);
	}

	@Override
	public void setUp() throws CommandException {
		// TODO Auto-generated method stub		
	}

	@Override
	public void process() throws CommandException {
		Group group;
		long groupID = 0;

		try {
			groupID = (Long)helper.getSessionAttribute("GroupID");

			if (groupID == 0)
				throw new CurrentUserNotInGroupException("You must be a part of a group to edit a group.");

			String name = helper.getString("name");
			String description = helper.getString("description");
			long version = helper.getLong("version");

			group = GroupInputMapper.find(groupID);
			group.setGroupName(name);
			group.setDescription(description);
			group.setVersion(version);
			
			UoW.getCurrent().registerDirty(group);
			UoW.getCurrent().commit();
		} catch (LostUpdateException e) {
			throw new GroupModifiedException();
		} catch (CommandException e) {
			throw e;
		} catch (Exception e) {
			throw new CommandException(e);
		}
	}

	@Override
	public void tearDown() throws CommandError {
		// TODO Auto-generated method stub
	}
}
